package com.grace.portal.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.grace.portal.entity.User;
import com.grace.portal.service.UserService;

/**
 * Controller shows the index page.
 * 
 */
@Controller
public class IndexController extends BaseController{

	@Resource(name = "userServiceImpl")
	private UserService userService;
	
    @RequestMapping(value = "/index")
    public String index(ModelMap modelMap) {
    	
        modelMap.addAttribute("theModelKey", "Spring says HI!");
        return "/index.ftl";
    }
    
    @RequestMapping(value = "/toLogin")
    public String toLogin(){
    	return "/login";
    }
    
    @RequestMapping(value = "/login",method=RequestMethod.POST)
    public String login(String userName,String password,HttpSession session,ModelMap modelMap){
    	
    	if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)){
    		modelMap.addAttribute("userName", userName);
        	modelMap.addAttribute("password", password);
        	
    		modelMap.addAttribute("message", "用户名或密码不能为空。");
    		return "forward:/toLogin";
    	}
    	User user = userService.Login(userName, password);
    	if(user == null){
    		modelMap.addAttribute("userName", userName);
        	modelMap.addAttribute("password", password);
        	
    		modelMap.addAttribute("message", "用户名或密码不正确。");
    		return "forward:/toLogin";
    	}
    	
    	session.setAttribute("currentUser", user);
    	
    	return "redirect:/main/index";
    }
    
    @RequestMapping(value = "/main/index",method=RequestMethod.GET)
    public String mainIndex(){
    	return "/main/index";
    }
    
    @RequestMapping(value = "/main/main",method=RequestMethod.GET)
    public String toMain(){
    	
    	return "/main/main";
    }
}
